#!/usr/bin/env python3
# Copyright 2025 The Emscripten Authors.  All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License.  Both these licenses can be
# found in the LICENSE file.

"""Update npm dependencies using npm-check-updates
"""

import os
import subprocess
import sys

script_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(os.path.dirname(script_dir))


def run(cmd, **args):
  print('->', ' '.join(cmd))
  return subprocess.check_output(cmd, text=True, cwd=root_dir, **args)


def main():
  if run(['git', 'status', '-uno', '--porcelain']).strip():
    print('tree is not clean')
    return 1

  output = run(['npx', 'npm-check-updates', '-u'], stderr=subprocess.STDOUT).strip()

  if not run(['git', 'status', '-uno', '--porcelain']).strip():
    print('no updates')
    return 0

  message = 'Automatic update of npm dependencies. NFC\n\n'
  message += 'This change was automatically generated by tools/maint/npm_update.py\n\n'
  lines = output.splitlines()
  assert lines[0].startswith('Upgrading ')
  assert lines[1] == ''
  assert lines[-1].startswith('Run npm install to install new versions')
  assert lines[-2] == ''
  lines = lines[2:-2]
  message += '\n'.join(lines) + '\n'

  run(['npm', 'install'])
  run(['git', 'checkout', '-b', 'npm_update'])
  run(['git', 'add', '-u', 'package.json', 'package-lock.json'])
  run(['git', 'commit', '-F', '-'], input=message)


if __name__ == '__main__':
  sys.exit(main())
